package top.choviwu.garbage.sort.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.choviwu.garbage.sort.annotation.GLog;
import top.choviwu.garbage.sort.annotation.Limit;
import top.choviwu.garbage.sort.entity.Log;
import top.choviwu.garbage.sort.ex.CrudException;
import top.choviwu.garbage.sort.mapper.LogMapper;
import top.choviwu.garbage.sort.redis.RedisRepository;
import top.choviwu.garbage.sort.util.CusAccessObjectUtil;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;

import static top.choviwu.garbage.sort.constant.Constants.BASE_SECOND;

@Aspect
@Component
@Slf4j
public class LimitAspect {


    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RedisRepository redisRepository;

    private final String PRE_LIST = "choviwu:garbage:ip:";

    private final String BLACK_LIST = "choviwu:garbage:black";



    @Pointcut(value = "@annotation(top.choviwu.garbage.sort.annotation.Limit)")
    public void point(){}

    @Around(value = "point()&&@annotation(limit)")
    public Object around(ProceedingJoinPoint joinPoint, Limit limit) throws Throwable {
        try {
            if(limit.limits()==-1){
                return joinPoint.proceed();
            }
            String ip = CusAccessObjectUtil.getIpAddress(request);

            Object value = redisRepository.get(PRE_LIST+ip);
            if(Objects.isNull(value)) {
                redisRepository.set(PRE_LIST+ip,String.valueOf(System.currentTimeMillis()),limit.limits());
                redisRepository.sSet(BLACK_LIST,ip);
                Object ret = joinPoint.proceed();
                return ret;
            }
            long currentTime = System.currentTimeMillis();
            if((currentTime - Long.valueOf((String)value) )/BASE_SECOND<limit.limits()){
                log.error("cached ip >>>>"+ip);
                throw new CrudException("操作太频繁，请等待"+(limit.limits()-((currentTime - Long.valueOf((String)value))/BASE_SECOND))+"秒后再试");
            }
            throw new CrudException("系统异常");
        }catch (Exception e){
            throw e;
        }
    }

}
